#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


// ./clinet server_ip server_port
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        std::cout << "Usage:./client server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    int server_port = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        std::cout << "create socket error" << std::endl;
        return 2;
    }

    //client 不需要显示进行bind, 因为bind只在服务端使用
    //TCP时面向连接的
    struct sockaddr_in server_addr;
    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(server_port);
    server_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());
    //connect底层会自动进行bind
    int n = ::connect(sockfd, (struct sockaddr*)&server_addr,sizeof(server_addr));
    if(n < 0)
    {
        std::cout << "connect error" << std::endl;
        return 3;
    }

    //echo client
    std::string message;
    while(true)
    {
        char inbuffer[1024];
        std::cout << "input message: ";
        std::getline(std::cin,message);
        
        n = write(sockfd,message.c_str(),message.size());
        if(n > 0)
        {
            int m = ::read(sockfd,inbuffer,sizeof(inbuffer));
            if(m > 0)
            {
                inbuffer[m] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            std::cout << "write error" << std::endl;
            break;
        }
    }

    ::close(sockfd);
    return 0;
}